package com.shensi.adminCollect.controller.station;


import com.alibaba.fastjson.JSONObject;
import com.shensi.adminCollect.common.constant.HttpStatus;
import com.shensi.common.core.controller.BaseController;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.common.core.page.PageDomain;
import com.shensi.common.core.page.TableDataInfo;
import com.shensi.common.core.page.TableSupport;
import com.shensi.adminCollect.common.utils.DateUtils;
import com.shensi.adminCollect.common.utils.StringUtils;
import com.shensi.adminCollect.domain.station.NonClassSettlement;
import com.shensi.adminCollect.domain.station.Station;
import com.shensi.adminCollect.domain.station.vo.QueryClassVo;
import com.shensi.adminCollect.service.station.IStationService;
import com.shensi.adminCollect.service.station.NonClassSettlementService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.shensi.common.core.domain.model.LoginUser;
import com.shensi.common.core.utils.SecurityUtils;
import com.shensi.common.core.domain.entity.SysUser;
@RestController
@RequestMapping("/nonOil")
@Slf4j
public class NonClassSettlementController extends BaseController {

    @Resource
    private NonClassSettlementService nonClassSettlementService;

    @Autowired
    private IStationService stationService;

    /**
     * 预班结 班结前数据
     * */
    @PostMapping("/initiateClassSe")
    @ApiOperation("预班结 班结前数据")
    public AjaxResult initiateClassSe(@RequestBody NonClassSettlement nonClassSettlement){
        if (Objects.isNull(nonClassSettlement.getStationId()) ) {
            return AjaxResult.error("未选择油站");
        }
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();
        // 班结人 收银员 为当前登录用户的用户名

        QueryClassVo queryClassVo = nonClassSettlementService.initiateClassSe(nonClassSettlement);
        queryClassVo.setCreateUser(user.getUserId().toString());
        queryClassVo.setCreateName(user.getUserName());
        return AjaxResult.success(queryClassVo);
    }

    /**
     * 查看班结列表
     */
    @PostMapping("/list")
    @ApiOperation("查看班结列表")
    public TableDataInfo selectNonClassSettlementList(@RequestBody NonClassSettlement nonClassSettlement){
        if(Objects.isNull(nonClassSettlement) || Objects.isNull(nonClassSettlement.getPageNum())
                || Objects.isNull(nonClassSettlement.getPageSize())){
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("请求参数异常");
            rspData.setRows(null);
            rspData.setTotal(0);
            return rspData;
        }
        if (StringUtils.isNotEmpty(nonClassSettlement.getBeginTime()) && StringUtils.isNotEmpty(nonClassSettlement.getEndTime())) {
            // 计算两个日期之间的差值
            long daysBetween = DateUtils.countDays(nonClassSettlement.getBeginTime(),nonClassSettlement.getEndTime());

            // 如果差值超过一个月，返回失败
            if (daysBetween > 31) {
                TableDataInfo rspData = new TableDataInfo();
                rspData.setCode(HttpStatus.ERROR);
                rspData.setMsg("仅可查询一个月");
                rspData.setRows(null);
                rspData.setTotal(0L);
                return rspData;
            }
        } else if((StringUtils.isNotEmpty(nonClassSettlement.getBeginTime()) && StringUtils.isEmpty(nonClassSettlement.getEndTime()))
                || (StringUtils.isEmpty(nonClassSettlement.getBeginTime()) && StringUtils.isNotEmpty(nonClassSettlement.getEndTime()))){
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("查询时间未选择范围");
            rspData.setRows(null);
            rspData.setTotal(0L);
            return rspData;
        }else {
            // 开始时间和结束时间为空的逻辑
            LocalDate today = LocalDate.now(); // 当前日期
            LocalDate sevenDaysAgo = today.minusDays(7); // 当前日期往前7天的日期

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 定义日期时间格式化模式

            LocalDateTime beginTime = LocalDateTime.of(sevenDaysAgo, LocalTime.MIN); // 开始时间为当天的最早时间（00:00:00）
            LocalDateTime endTime = LocalDateTime.of(today, LocalTime.MAX); // 结束时间为当天的最晚时间（23:59:59）

            String beginTimeStr = beginTime.format(formatter); // 格式化开始时间为字符串
            String endTimeStr = endTime.format(formatter); // 格式化结束时间为字符串

            // 将开始时间和结束时间的字符串赋值给相应的变量
            nonClassSettlement.setBeginTime(beginTimeStr);
            nonClassSettlement.setEndTime(endTimeStr);
        }

        log.info("selectNonClassSettlementList查看班结列表 请求参数 ：[{}]", JSONObject.toJSONString(nonClassSettlement));
        PageDomain pageDomain = TableSupport.buildPageRequest();
        pageDomain.setPageNum(nonClassSettlement.getPageNum());
        pageDomain.setPageSize(nonClassSettlement.getPageSize());
        nonClassSettlement.setStationIdList(getStationIdList(nonClassSettlement));
        startPage(pageDomain);
        List<NonClassSettlement> classSettlementList = nonClassSettlementService.selectNonClassSettlementList(nonClassSettlement);
        return getDataTable(classSettlementList);
    }

    private List<Long> getStationIdList(NonClassSettlement nonClassSettlement){
        List<Long> stationIdList = new ArrayList<>();
        if(Objects.nonNull(nonClassSettlement.getStationId())){
            stationIdList.add(nonClassSettlement.getStationId());
        } else if(Objects.nonNull(nonClassSettlement.getEnterpriseId())){
            List<Station> stationList = stationService.getStationByEnterpriseId(nonClassSettlement.getEnterpriseId());
            for (Station station : stationList) {
                stationIdList.add(station.getStationId());
            }
        }
        return stationIdList;
    }

    /**
     *
     * 查看班结详情
     * */
    @GetMapping("/details")
    @ApiOperation("查看班结详情")
    public AjaxResult selectNonClassSettlementDetails(@RequestParam("classNo") String classNo){
        if(StringUtils.isBlank(classNo)){
            return AjaxResult.error("请求参数不为空");
        }
        log.info("查看班结详情请求参数：[{}]",classNo);
        QueryClassVo queryClassVo = nonClassSettlementService.selectNonClassSettlementDetails(classNo);
        log.info("查看班结详情 返回结果：[{}]",JSONObject.toJSONString(queryClassVo));
        return AjaxResult.success(queryClassVo);
    }
}
